package zy.service.sell.day.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.sell.day.DayDAO;
import zy.entity.sell.day.T_Sell_Day;
import zy.entity.sell.day.T_Sell_Weather;
import zy.service.sell.day.DayService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.URLUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@Service
public class DayServiceImpl implements DayService{
	@Resource
	private DayDAO dayDAO;
	@Override
	public T_Sell_Weather weather(Map<String, Object> param) {
		String city = dayDAO.cityByCode(param);//查询店铺的城市
		String today = (String)param.get("today");
		String shop_code = (String)param.get(CommonUtil.SHOP_CODE);
		Object companyid = param.get(CommonUtil.COMPANYID);
		/*if(null == city || "".equals(city)){
			city = (String)param.get("_city"); 
			param.put("city", city);
			if(city == null || "".equals(city)){
				return null;
			}else{
				param.put("city", city);
			}
		}else{
		}*/
		param.put("city", city);
		//根据城市查看是否天气是否已经存在
		T_Sell_Weather weather = dayDAO.weather(param);
		if(null == weather){//还没保存店铺今天的天气
			//去系统天气表里查
			weather = dayDAO.sysWeather(param);
			if(null == weather){
				weather = buildWeather(param);
				if(weather != null){
					if("1".equals(weather.getWe_we_id())){
						param.put("yestoday", DateUtil.getDateAddDays(-1));
						T_Sell_Weather _weather = dayDAO.tomorrow(param);
						if(null != _weather){
							weather.setWe_we_id(_weather.getWe_tomorrow());
							weather.setWe_name(_weather.getWe_name());
						}
					}
					weather.setWe_city(city);
					weather.setWe_date(today);
					dayDAO.saveSysWeather(weather);//保存系统天气表
				}
				weather.setWe_date(today);
				weather.setWe_shop_code(shop_code);
				weather.setCompanyid((Integer)companyid);
				dayDAO.saveWeather(weather);//保存店铺天气表
			}else{
				if("1".equals(weather.getWe_we_id())){
					param.put("yestoday", DateUtil.getDateAddDays(-1));
					T_Sell_Weather _weather = dayDAO.tomorrow(param);
					if(null != _weather){
						weather.setWe_we_id(_weather.getWe_tomorrow());
						weather.setWe_name(_weather.getWe_name());
					}
				}
				weather.setWe_date(today);
				weather.setWe_shop_code(shop_code);
				weather.setCompanyid((Integer)companyid);
				dayDAO.saveWeather(weather);//保存店铺天气表
			}
		}else{
			if(weather.getWe_max_tmp() == 0){
			}
		}
		if(null != weather){
			weather.setWe_city(city);
		}
		return weather;
	}
	@Transactional
	@Override
	public T_Sell_Day queryDay(Map<String, Object> paramMap) {
		T_Sell_Day day = dayDAO.queryDay(paramMap);
		if(null == day){
			day = new T_Sell_Day();
			day.setDa_come(0);
			day.setDa_receive(0);
			day.setDa_try(0);
			day.setCompanyid((Integer)paramMap.get(CommonUtil.COMPANYID));
			day.setDa_shop_code((String)paramMap.get(CommonUtil.SHOP_CODE));
			day.setDa_date((String)paramMap.get("today"));
			dayDAO.saveDay(day);
		}
		return day;
	}

	@Override
	public void come(Map<String, Object> paramMap) {
		dayDAO.come(paramMap);
	}
	
	@Override
	public void receive(Map<String, Object> paramMap) {
		dayDAO.receive(paramMap);
	}
	
	@Override
	public void comereceive(Map<String, Object> paramMap) {
		dayDAO.comereceive(paramMap);
	}
	
	@Override
	public void doTry(Map<String, Object> paramMap) {
		dayDAO.doTry(paramMap);
	}
	@Cacheable(value="DEFAULT_CACHE")
	public JSONObject getCityJSON(){
		URL url = null;
		URLConnection connectionData = null;
		BufferedReader br = null;
		JSONObject jsonData = null;
		try {
			url = new URL(URLUtil.URL_CITYJSON);
			connectionData = url.openConnection();
			connectionData.setConnectTimeout(1000);

			br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));
			StringBuffer sb = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			jsonData = JSONObject.parseObject(sb.toString());
		} catch (MalformedURLException e) {
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
		}finally{
			try {
				if(br != null){br.close();}
			} catch (IOException e) {
			}
		}
		return jsonData;
	}
	public T_Sell_Weather buildWeather(Map<String,Object> paramMap){
		String city = (String)paramMap.get("city");
		JSONObject cityJSON = getCityJSON();
		JSONObject cityJson = cityJSON.getJSONObject(URLUtil.RESULT);
		Iterator<?> it = cityJson.keySet().iterator();  
		String cityid = "";
		while(it.hasNext()){
			String key = (String) it.next();  
			JSONObject _cityjson = cityJson.getJSONObject(key);
            String value = _cityjson.getString(URLUtil.CITYNAME);
            if(null != value && city.equals(value)){
            	cityid = _cityjson.getString(URLUtil.WEAID);
            	break;
            }
		}
		T_Sell_Weather weather = new T_Sell_Weather();
		JSONObject _weatherJson = buildWeather(cityid);
		if(!"0".equals(_weatherJson.getString("success"))){
			JSONObject weatherJson = _weatherJson.getJSONObject(URLUtil.RESULT);
			weather.setWe_max_tmp(weatherJson.getInteger(URLUtil.TEMPHIGH));
			weather.setWe_min_tmp(weatherJson.getInteger(URLUtil.TEMPLOW));
			weather.setWe_we_id(weatherJson.getInteger(URLUtil.WEATID));
			weather.setWe_wind(weatherJson.getString(URLUtil.WIND));
			weather.setWe_name(weatherJson.getString(URLUtil.WEATHER));
			
			JSONObject futureJson = buildTomorrow(cityid);
			if(!"0".equals(futureJson.getString("success"))){
				JSONArray _futureJsons = futureJson.getJSONArray(URLUtil.RESULT);
				for(int i =0;i<_futureJsons.size();i++){
					JSONObject _futureJson = (JSONObject)_futureJsons.get(i);
					String wdate = _futureJson.getString("days");
					if(DateUtil.getDateAddDays(1).equals(wdate)){
						weather.setWe_tomorrow(_futureJson.getInteger(URLUtil.WEATID));
					}
				}
			}
		}
		return weather;
	}
	
	public JSONObject buildTomorrow(String cityid){
		URL url = null;
		URLConnection connectionData = null;
		BufferedReader br = null;
		JSONObject jsonData = null;
		try {
			url = new URL(URLUtil.URL_TOMORROW+cityid);
			connectionData = url.openConnection();
			connectionData.setConnectTimeout(1000);

			br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));
			StringBuffer sb = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			jsonData = JSONObject.parseObject(sb.toString());
		} catch (MalformedURLException e) {
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
		}finally{
			try {
				if(br != null){br.close();}
			} catch (IOException e) {
			}
		}
		return jsonData;
	}
	public JSONObject buildWeather(String cityid){
		URL url = null;
		URLConnection connectionData = null;
		BufferedReader br = null;
		JSONObject jsonData = null;
		try {
			url = new URL(URLUtil.URL_WEATHER+cityid);
			connectionData = url.openConnection();
			connectionData.setConnectTimeout(1000);

			br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));
			StringBuffer sb = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			jsonData = JSONObject.parseObject(sb.toString());
		} catch (MalformedURLException e) {
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
		}finally{
			try {
				if(br != null){br.close();}
			} catch (IOException e) {
			}
		}
		return jsonData;
	}
	
	@Override
	public Integer countreceive(Map<String, Object> paramMap) {
		return dayDAO.countreceive(paramMap);
	}
	
}
